//
//  ArticoloCommentiViewController.m
//  
//
//  Created by Dario Trisciuoglio on 09/06/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ArticoloCommentiViewController.h"
#import "ArticoloCommentiCell.h"
#import "AutoDownloadImageView.h"
#import "MTCostants.h"

@implementation ArticoloCommentiViewController

@synthesize urlParserView;
@synthesize spinner;
@synthesize spinnerView;
@synthesize TableView;

@synthesize titoloArticolo;
@synthesize descrizioneArticolo;
@synthesize imageArticoloURL;

#pragma mark - spinner methods

-(void)addIndicator{
    [self.view addSubview:spinnerView];
    [spinner startAnimating];
    [self.view setUserInteractionEnabled:NO];
}

-(void)removeIndicator{
    [spinner stopAnimating];
    [self.view setUserInteractionEnabled:YES];
    [spinner release];    
    [spinnerView removeFromSuperview];
    [spinnerView release];
}

- (void)applicaColore {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.5];
	self.spinnerView.backgroundColor = [UIColor clearColor];
	[UIView commitAnimations];
}

- (void)controlloDownloadXML{
	[self parseXMLFileAtURL:urlParserView];
    [self applicaColore];
    [self.TableView reloadData];
    [super performSelector:@selector(removeIndicator) withObject:urlParserView afterDelay:0.01];
}

#pragma mark - View

- (void)viewDidLoad {
	self.title = @"Commenti";
	[self parseXMLFileAtURL:urlParserView];
    [self addIndicator];
    [super performSelector:@selector(controlloDownloadXML) withObject:urlParserView afterDelay:0.01];
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; }

- (void)viewDidUnload {}

#pragma mark parser methods

- (void)parseXMLFileAtURL:(NSString *)URL {
	// inizializziamo la lista degli elementi
	elencoCommenti = [[NSMutableArray alloc] init];
	// dobbiamo convertire la stringa "URL" in un elemento "NSURL"
	NSURL *xmlURL = [NSURL URLWithString:URL];
    //NSLog(@"%@", URL);
	// inizializziamo il nostro parser XML
	commentiParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
	[commentiParser setDelegate:self];
	// settiamo alcune proprietà
	[commentiParser setShouldProcessNamespaces:NO];
	[commentiParser setShouldReportNamespacePrefixes:NO];
	[commentiParser setShouldResolveExternalEntities:NO];
	// avviamo il parsing del feed RSS
	[commentiParser parse];
    //NSLog(@"Avviamo il parsing");
    //NSLog(@"%@", elencoCommenti);
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{			
	currentElement = [elementName copy];
	if ([elementName isEqualToString:@"item"]) {
		//inizializza tutti gli elementi
        item = [[NSMutableDictionary alloc] init];
        currentNome = [[NSMutableString alloc] init];
        currentAvatar = [[NSMutableString alloc] init];
        currentCommento = [[NSMutableString alloc] init];
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
	if ([elementName isEqualToString:@"item"]) {
		//salva tutte le proprietà del feed letto nell'elemento "item", per poi inserirlo nell'array "elencoCommenti"
		[item setObject:currentNome forKey:@"nome"];
        [item setObject:currentAvatar forKey:@"avatar"];
        [item setObject:currentCommento forKey:@"commento"];
		[elencoCommenti addObject:[item copy]];
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{;
	// salva i caratteri per l'elemento corrente
    if ([currentElement isEqualToString:@"nome"]) {
		[currentNome appendString:string];
	} else if([currentElement isEqualToString:@"avatar"]) {
		[currentAvatar appendString:string];
	}else if([currentElement isEqualToString:@"commento"]) {
		[currentCommento appendString:string];
	}

}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    //NSLog(@"Parser end");
    [parser release];
}

#pragma mark AutoDownload methods

-(void)autoDownload:(AutoDownloadImageView *)autoDowload didFailWithError:(NSError *)error {
	//NSLog(@"SOMETHING WRONG");
}

-(void)autoDownloadImageViewFinishDownloading:(AutoDownloadImageView *)autoDowload {
    //NSLog(@"OK");
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

#pragma mark - UITableViewDelegate Methods


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        // prende l'altezza della cella nello xib    
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        return cell.frame.size.height;
    
    } else {
        // calcola l'altezza in base al contenuto della label nello xib
        NSString *text = [[elencoCommenti objectAtIndex:indexPath.row] objectForKey:@"commento"];
        [text stringByReplacingOccurrencesOfString:@" " withString:@""];
        [text stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        [text stringByReplacingOccurrencesOfString:@"	" withString:@""];
        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
        CGFloat height = size.height;
        //NSLog(@"Larghezza e altezza della cella %f,%f ", size.width, size.height);

        if (height <= 50.000000f) {
            height = 60.000000f;
        }
        
        //NSLog(@"Larghezza e altezza della cella %f,%f ", size.width, height);
        return height + (CELL_CONTENT_MARGIN * 2);
        //return height;
    }
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0)
        
        return 1;
    
    else
        
        return [elencoCommenti count];
}
    
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {        
    
    static NSString *CellIdentifier = @"ArticoloCommentiCell";
    
    ArticoloCommentiCell *articoloCommentiCell = (ArticoloCommentiCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (articoloCommentiCell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ArticoloCommentiCell" owner:self options:nil];
        for (id currentObject in topLevelObjects){
            if ([currentObject isKindOfClass:[UITableViewCell class]]){
                articoloCommentiCell =  (ArticoloCommentiCell *) currentObject;
                break;
            }
        }
    }
    
    if (indexPath.section == 0) {
        
        articoloCommentiCell.titoloArticolo.text = titoloArticolo;
        articoloCommentiCell.testoArticolo.text = descrizioneArticolo;
        [articoloCommentiCell dettaglioArticoloViewSetIsInvisibile:NO];
        [articoloCommentiCell retain];
        
    } else if (indexPath.section == 1) {
        
        [articoloCommentiCell dettaglioArticoloViewSetIsInvisibile:YES];

        id avatar = [[elencoCommenti objectAtIndex:indexPath.row] objectForKey:@"avatar"];
        avatar = [avatar stringByReplacingOccurrencesOfString:@" " withString:@""];
        avatar = [avatar stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        avatar = [avatar stringByReplacingOccurrencesOfString:@"	" withString:@""];
        NSURL *url = [NSURL URLWithString:avatar];
        
        AutoDownloadImageView *img = [[AutoDownloadImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)URL:url persistency:YES forceDownload:NO];
        [img setDelegate:self];
        [articoloCommentiCell.dettaglioCommento addSubview:img];
        [img release];
        
        id nome = [[elencoCommenti objectAtIndex:indexPath.row] objectForKey:@"nome"];
        [nome stringByReplacingOccurrencesOfString:@" " withString:@""];
        [nome stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        [nome stringByReplacingOccurrencesOfString:@"	" withString:@""];
        articoloCommentiCell.nomeAutore.text = nome;
        
        id commento = [[elencoCommenti objectAtIndex:indexPath.row] objectForKey:@"commento"];
        [commento stringByReplacingOccurrencesOfString:@" " withString:@""];
        [commento stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        [commento stringByReplacingOccurrencesOfString:@"	" withString:@""];
        
        articoloCommentiCell.commento.text = commento;
        
        [articoloCommentiCell retain];
    }
    
    return articoloCommentiCell;

}	


- (void)dealloc {
	[currentElement release];
	[commentiParser release];
	[elencoCommenti release];
	[item release];
    [AutoDownloadImageView release];
	[currentNome release];
	[currentAvatar release];
    [currentCommento release];
    [super dealloc];
}
@end